<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
        搜索:<input type="text" v-model="searchVal">
        <ul>
            <li v-for="(p,index) in filterPersons" :key="index">
                {{index}} -- {{p.name}} -- {{p.age}}
            </li>
        </ul>
        <button @click="sortByAge(1)">年龄升序</button>
        <button @click="sortByAge(2)">年龄降序</button>
        <button @click="sortByAge(0)">原本顺序</button>
    </div>

</body>
<script src="../../public/vue.dev.js"></script>
<script>
    const vm = new Vue({
        el: '#app',
        data: {
            sortType:0, // 0:原本顺序 1:升序 2:降序
            searchVal:'z',
            persons: [
                {'name':'zhangsan','age':10},
                {'name':'lisi','age':14},
                {'name':'wangwu','age':18},
            ],
        },
        methods: {
            sortByAge(sortType){
                this.sortType = sortType;
            }
        },
        computed: {
            filterPersons() {
                // 取出相关的数据
                let {searchVal, persons,sortType} = this;
                // 过滤之后的值
                persons = persons.filter(p =>
                    p.name.indexOf(searchVal) != -1
                );
                // alert(sortType);
                // 排序
                if (sortType != 0) {
                    persons = persons.sort(function (p1,p2) {
                        if (sortType == 2) {
                            return p2.age - p1.age;
                        } else {
                            return p1.age - p2.age;
                        }
                    });
                }
                return persons;
            }
        }
    });
</script>
</html>
